<template>
  <div class="user-info-wrapper">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本信息" name="basicInfo">
        <el-form
          :model="userForm"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          class="user-info-form"
        >
          <el-form-item label="账号">
            <el-input v-model="userForm.account" disabled />
          </el-form-item>

          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" />
          </el-form-item>

          <el-form-item label="头像">
            <el-upload
              align="center"
              class="avatar-uploader"
              action=""
              :http-request="uploadAvatar"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="userForm.avatar"
                :src="userForm.avatar"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userForm.phone" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="修改密码" name="changePassword">
        <el-form
          :model="passwordForm"
          :rules="passwordRules"
          ref="passwordFormRef"
          label-width="100px"
          class="password-form"
        >
          <el-form-item label="原密码" prop="password">
            <el-input
              v-model="passwordForm.password"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item label="新密码" prop="newPwd">
            <el-input
              v-model="passwordForm.newPwd"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="repeatedPwd">
            <el-input
              v-model="passwordForm.repeatedPwd"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="changePassword"
              >修改密码</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { uploadImg, updataUser, updatePassword } from "@/api/user";

export default {
  data() {
    // 验证新密码规则
    const validatePass = (rule, value, callback) => {
      const reg = /^[0-9a-zA-Z]{6,10}$/;
      if (!value) {
        callback(new Error("请输入新密码"));
      } else if (!reg.test(value)) {
        callback(new Error("密码必须是6-10位数字或字母"));
      } else {
        callback();
      }
    };

    // 验证确认密码是否与新密码一致
    const validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.passwordForm.newPwd) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };

    return {
      activeTab: "basicInfo",
      userForm: {
        account: "",
        username: "",
        avatar: "",
        phone: null,
        email: null,
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        phone: [
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
        email: [{ type: "email", message: "邮箱格式不正确", trigger: "blur" }],
      },
      passwordForm: {
        password: "",
        newPwd: "",
        repeatedPwd: "",
      },
      passwordRules: {
        password: [
          { required: true, message: "请输入原密码", trigger: "blur" },
          {
            min: 6,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur",
          },
        ],
        newPwd: [{ required: true, validator: validatePass, trigger: "blur" }],
        repeatedPwd: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
      },
    };
  },

  mounted() {
    if (this.userInfo) {
      const { username, account, avatar, phone, email } = this.userInfo;
      this.userForm = {
        username,
        account,
        avatar,
        phone,
        email,
      };
    }
  },

  computed: {
    ...mapState("user", ["userInfo"]),
  },
  methods: {
    onSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            let res = await updataUser(this.userForm);
            if (res.code == 200) {
              this.$message.success(res.data);
              // 获取用户更新后的用户信息
              this.$store.dispatch("user/getInfo");
            } else {
              this.$message.error(res.msg);
            }
          } catch (e) {}
        }
      });
    },

    changePassword() {
      this.$refs.passwordFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const passwordData = {
              password: this.passwordForm.password,
              newPwd: this.passwordForm.newPwd,
              repeatedPwd: this.passwordForm.repeatedPwd,
              account: this.userInfo.account,
            };

            let res = await updatePassword(passwordData);
            if (res.code == 200) {
              this.$message.success(res.data);
              // 退出登录
              await this.$store.dispatch("user/logout");
              this.$router.push("/login");
            } else {
              this.$message.error(res.msg);
            }
          } catch (e) {
            this.$message.error(e.message || "修改密码失败");
          }
        } else {
          return false;
        }
      });
    },

    beforeAvatarUpload(file) {
      const isImage = file.type === "image/jpeg" || file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error("头像必须是 JPG 或 PNG 格式！");
      }
      if (!isLt5M) {
        this.$message.error("头像大小不能超过 3MB！");
      }
      return isImage && isLt5M;
    },

    async uploadAvatar(option) {
      const formData = new FormData();
      formData.append("file", option.file);
      try {
        const res = await uploadImg(formData);
        if (res.code === 200) {
          // 更新头像地址
          this.userForm.avatar = res.data;
          // 通知 el-upload 上传成功
          option.onSuccess(res.data);
          this.$message.success("上传成功");
        } else {
          this.$message.error("上传失败");
        }
      } catch (e) {
        this.$message.error("上传出错");
      }
    },
  },
};
</script>

<style scoped>
.user-info-wrapper {
  width: 500px;
  padding: 20px;
  margin-left: 40px;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 6px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 100px;
  text-align: center;
}

.password-form {
  max-width: 400px;
}
</style>
